// index.js
//获取应用实例
var app = getApp();
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');
var tls = require('../../utils/tls.js');
//获取解密电话号码的js模块
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
var imutil = require("../../utils/imutil.js");

var util = require('../../utils/util.js');

Page({
  data: {
    userName: '',
    telephone: wx.getStorageSync('isRegistered'),
    companyName: '',
    position: '',
    sourcesToSelect: [
      '深圳市司法局或各区司法局',
      '深圳创客法律中心',
      '沃本(深圳)企业咨询管理有限公司',
      '其他'
    ],

    type:0,// 聊天类型

    email: '',
    selectedSource: '',
    userSig: '',
    loginBtnShow: false,
    registerBtnValue: "注册并登录",
    FaceUrl:'',
    nickName:'',
    navH:0
  },


  onLoad: function() {
    
    let that=this

    this.setData({
      navH: app.globalData.navHeight
    })
    
  },


  // get the user name
  userNameInput: function(e) {
    this.setData({
      userName: e.detail.value
    });
  },
  //end get the user name

  // get the company name
  companyNameInput: function(e) {
    this.setData({
      companyName: e.detail.value
    });

    app.globalData.companyName = e.detail.value;

    wx.setStorage({//存储到本地
      key: "companyName",
      data: e.detail.value
    })
  },
  //end get the company name

  // get the position 
  positionInput: function(e) {
    this.setData({
      position: e.detail.value
    })
  },
  //end get the position

  //click the button to get the telephone,this is react function
  getPhoneNumber: function(e) {
    var that = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData);
    var session_key = app.globalData.session_key;
    console.log("get the APP variable,the session key is " + session_key);
    var encryptedData = e.detail.encryptedData;
    var iv = e.detail.iv;
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showModal({
        title: '本版本仅支持自动登录，且获取的信息仅限电话号码，不会窃取用户隐私，请放心授权',
        showCancel: false,
        content: '',
        success: function(res) {

        }
      })
    } else {
      // 同意授权的情况下，解密数据，获取电话号码
      var phoneNumbber = decryptPhoneNumber(encryptedData, iv);
      console.log("get the phoneNumbber successfully,it's value is " + phoneNumbber);
      //set the value to global variable
      app.globalData.phoneNumber = phoneNumbber;

      // set the value to the input that in wxml page
      that.setData({
        telephone: wx.getStorageSync('isRegistered')
      });
      console.log("the telephone is %o", that.data.telephone);

      // show the notice that get the telephone successfully
      wx.showToast({
        title: '获取电话号码成功',
        icon: 'success',
        duration: 1000
      });
    }
  },
  // end getPhoneNumber function

  //get the email
  emailInput: function(e) {
    this.setData({
      email: e.detail.value
    })
  },
  //end emailInput
  //select the source that user know this APP
  bindPickerChange: function(e) {
    var that = this;
    console.log(e);
    var index = e.detail.value;
    console.log('picker发送选择改变，携带值为:');
    console.log(this.data.sourcesToSelect[index]);
    this.setData({
      selectedSource: this.data.sourcesToSelect[index]
    })
    console.log('selectedSource is :' + that.data.selectedSource);
  },
  // end bindPickerChange
  // this function handle the register button click

  // editUser


  userRegister: function(e) {
    var that = this;
    // the user input can't be empty

    console.log(that.data.userName)
    console.log(that.data.companyName)
    console.log(that.data.position)
    console.log(that.data.email)


    if (that.data.userName.length == 0 ||that.data.companyName.length == 0 || that.data.position.length == 0 ||  that.data.email.length == 0) {
      wx.showToast({
        title: '输入不得为空',
        icon: 'success',
        duration: 2000
      });
    } else 
    {

      console.log(that.data);

      console.log(that.data.userName)
      console.log(that.data.companyName)
      console.log(that.data.position)
      console.log(that.data.email)

      wx.request({
        url: util.api+"/iim/im/editUser",
        data: {
          token:wx.getStorageSync('token'),
          name:that.data.userName,
          position:that.data.position,  //职位
          mailbox:that.data.email,    //邮箱
          company:that.data.companyName,// 公司名称
        },

        success: function(res) {
          var tmpsig = res.data;

          console.log("the return of getUserSigByTelephone is:" + tmpsig);
        

          console.log(tmpsig)

          if(tmpsig.success){

            wx.setStorageSync('userName', that.data.userName);

              wx.showToast({
                title: tmpsig.msg,
                icon: 'success',
                duration: 2000
              });
              
              setTimeout(function () {
                console.log("now we go to login page");
                wx.switchTab({
                  url: '../login/login'
                })
              }, 2000);

          }

          if(!tmpsig.success){
            wx.showToast({
              title: tmpsig.msg,
              duration: 2000
            });
         
          }

        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        }
      })



    

      // sendUserInfo2Server(that);

      // wx.setStorageSync('isRegistered', true);
      // registered successfully
    

      // navigate to login page
      //pause（setTimeout），let showToast run over
    
        //end navigate to login page


    }

  },
  //end the function userRegister


  onGotUserInfo: function(e) {
    var that=this;
    // get the user head image
    /**
     * 获取用户信息
     */


     console.log(wx.getStorageSync('userId'))

     let userId=wx.getStorageSync('userId')

     console.log(userId)

     if(userId){
      wx.request({
        url: util.api+"/iim/im/viewUser",
        data: {
          id:wx.getStorageSync('userId')
        },
  
        success: function(res) {
          var tmpsig = res.data;
  
          console.log("the return of getUserSigByTelephone is:" + tmpsig);
        
  
          console.log(tmpsig)
  
          if(tmpsig.success){
  
            // wx.setStorageSync('userName', that.data.userName);
    
          
            that.setData({
              userName:tmpsig.body.data.name,
              companyName:tmpsig.body.data.companyName,
              position:tmpsig.body.data.position,
              email:tmpsig.body.data.email,
            })
  

          }
  
          if(!tmpsig.success){
            wx.showToast({
              title: tmpsig.msg,
              duration: 2000
            });
          }
        },
        fail: function(resp) {
          console.log("getUserSigByTelephone failed,the response is %o", resp)
          return false;
        }
      })
  
     }


  },
  //end onLoad

  onShow: function(e) {

    this.onGotUserInfo()


    // var isRegistered = wx.getStorageSync("isRegistered");
    // if (isRegistered) {
    //   console.log("the user has been registered");
    //   this.setData({
    //     loginBtnShow: "disable",
    //     btnValue: "已经注册"
    //   });
    // }
  },
  //end onShow

  //call some test function
  test: function() {
    var that = this;
    console.log("this is test");
    // access xuezhou.xyz 
    wx.request({
      url: "https://www.xuezhou.xyz/consultantRegister",
      data: {
        "telephone": that.data.telephone,
        "userName": that.data.userName,
        "companyName": that.data.companyName,
        "position": that.data.position,
        "email": that.data.email,
        "Source": that.data.selectedSource
        
        // "telephone": "17722656614",
        // "userName": "周江",
        // "companyName": "华商林李黎",
        // "position": "律师助理",
        // "email": "1043521500@qq.com",
        // "Source": "深圳创客法律中心"
      },
      success: function(res) {

        console.log("the return of consultantRegister is:" + res.data);
        console.log(res);
      },
      fail: function() {

      },
      complete: function(res) {
        console.log("the return of consultantRegister complete is:" + res.data);
        console.log(res);
      } //请求完成后执行的函数
    })
    // 结束wx.request
  },


  navBack(){

    let that=this

    wx.navigateBack({
      delta: 1,
    })


  },

})
//end Page

//user defined function
// 同意授权的情况下，解密数据，获取电话号码
function decryptPhoneNumber(encryptedData, iv) {
  // var appId = app.globalData.appid;
  // var sessionKey = app.globalData.session_key;
  // var iv = 'r7BXXKkLb8qrSNn05n0qiA==';

  // var pc = new WXBizDataCrypt(appId, sessionKey);
  // var data = pc.decryptData(encryptedData, iv);
  // console.log('解密后 data: ', data);

  var appId = app.globalData.appid;
  var sessionKey = app.globalData.session_key;
  var pc = new WXBizDataCrypt(appId, sessionKey)

  var data = pc.decryptData(encryptedData, iv)
  if (data) {
    console.log('解密后 data: ', data);
    return data.phoneNumber;
  } else {
    console.log("the data is cleared,please reopen the mini prigram");
    wx.showModal({
      title: '获取手机号失败，请完全退出并重新进入小程序',
      icon: 'fail',
      duration: 3000
    });

    //暂停（setTimeout）2秒，让showToast可以执行完毕
    setTimeout(function() {
      console.log("must logout")
      return false;
    }, 3000)
  }

}
//end decryptPhoneNumber

//send user info to server 
function sendUserInfo2Server(that) {
  wx.request({
    url: "https://www.xuezhou.xyz/consultantRegister",
    data: {
      "telephone": that.data.telephone,
      "userName": that.data.userName,
      "companyName": that.data.companyName,
      "position": that.data.position,
      "email": that.data.email,
      "Source": that.data.selectedSource,
      "FaceUrl":app.globalData.FaceUrl
    },
    success: function(res) {
      console.log("the return of consultantRegister is:" + res.data);
      console.log(res);
    },
    fail: function(resp) {
      console.log("registered failed，the response is %o", resp);
      return false;
    },
    complete: function(res) {
      
    } //请求完成后执行的函数
  })
  // 结束wx.request
}
// end sendUserInfo2Server